﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Data.Linq;
using System.Drawing;
using Website.Logger;
using DAL;
using BOL;
using System.Web.Script.Services;
using System.Web.Services;
using UtilityExtensions;


namespace UILGestion.ObraAdmin.Chart
{
    public partial class Cuota003Chart : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                FormatForm();
            }
        }
        private void FormatForm()
        {
            periodoDDL.SelectedValue = DateTime.Now.Year.ToString();

        }


        public void LoadChart(int idObra)
        {
            //por   cada mes segun el consumo en ordenes de compra con FR
            // 1.- Traemos  las compras desde el mes  segun los FR
            //2.- Agrupammos los documentos por el meses , OJO:el total esta en soles
            this.idObra.Value = idObra.ToString(); 
            
            Chart1.Titles[0].Text = String.Format ("Proyeccion vs. Compras (S/.)"); //TP:{0:N3}", ObraTC);
            BindDataItem();

            
                   

            //var qqp = from a in DbUtil.Db.Presupuesto
            //        where a.idObra == idObra
            //        select a.abreviacion;

            //var qqjup = from a in DbUtil.Db.EstructuraCostos
            //          where a.idObra == idObra
            //          select a.descripcion;


            //Chart1.Series["Default"].Points.DataBindXY(qqp, "Name", qqjup, "Sales");

        }


        public Cuota003Chart()

        {
            bol = new PresupuestoBL();
        }
        private PresupuestoBL bol;

        
        //protected void DeleteItem(object sender, EventArgs e)
        //{
        //    try
        //    {

        //        ImageButton lnkRemove = (ImageButton)sender;
        //        int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

        //        var rendicionItem = DbUtil.Db.Recursos.SingleOrDefault(p => p.idInternal == idInternal);

        //        bol.deleteRecurso(idInternal);
                
        //        updateTotalesview();
        //        BindDataItem();


        //    }
        //    catch (SqlException sqlex)
        //    {
        //        WebServerSideSqlError.Log(sqlex);
        //        ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
        //         "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


        //    }
        //    catch (Exception ex)
        //    {
        //        WebServerSideError.Log(ex);
        //        ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
        //         "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

        //    }

        //}
        //protected void AddItem(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        Button lnkdivrecurso = (Button)sender;

        //        TextBox idinsumoTxt =
        //            ((TextBox)itemGridView.FooterRow.FindControl("codigoTxt"));
                
        //        TextBox cantidadTxt =
        //            ((TextBox)itemGridView.FooterRow.FindControl("cantidadTXT"));
        //        TextBox totalTxt =
        //            ((TextBox)itemGridView.FooterRow.FindControl("totalTXT"));
              

                
               
        //        dbGestionDataContext _db=new dbGestionDataContext(Parametros.strConnString);
                
        //        bol.AddRecurso(_db, idinsumoTxt.Text, cantidadTxt.Text.ToDecimal().Value,
        //            totalTxt.Text.ToDecimal().Value, idParent.Value.ToInt());
                
        //        updateTotalesview();
        //        BindDataItem();
        //        // GridUpdatePanel.Update();
        //    }
        //    catch (SqlException sqlex)
        //    {
        //        WebServerSideSqlError.Log(sqlex);
        //        ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
        //         "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "").Replace("\r", "").Replace("\n", "") + "');", true);


        //    }
        //    catch (Exception ex)
        //    {
        //        WebServerSideError.Log(ex);
        //        ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
        //         "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

        //    }

        //}
        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                

                GridView gv = ((GridView)sender);

                
                TextBox totalTxt =
                    ((TextBox)gv.Rows[e.RowIndex].FindControl("totalTxt"));


                short mes = short.Parse(gv.DataKeys[e.RowIndex].Values[0].ToString());
                

                 int idEmpleadoEmisor = int.Parse(System.Web.HttpContext.Current.Session["idEmpleado"].ToString());


               dbGestionDataContext _db=new dbGestionDataContext(Parametros.strConnString);
               
                Empleado empleado= DbUtil.Db.Empleados.Single(p=>p.idInternal==idEmpleadoEmisor);
                ObraIndicador indicador = _db.ObraIndicadors.Single(p => p.idObra == idObra.Value.ToInt()
                                                                    & p.anio == periodoDDL.SelectedValue.ToInt()
                                                                    & p.mes == mes);

                indicador.UpdateTotalProyectado(totalTxt.Text.ToDecimal().Value, empleado.usuario);
                
                _db.SubmitChanges();
                
                gv.EditIndex = -1;
                itemGridView.FooterRow.Visible = true;
                BindDataItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);
                gv.EditIndex = e.NewEditIndex;
                BindDataItem();
                gv.FooterRow.Visible = false;
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        public void BindDataItem()
        {

            ProyeccionBL bol = new ProyeccionBL();
            var proyeccion = bol.GetObtenerProyeccionCompra(idObra.Value.ToInt(), periodoDDL.SelectedValue.ToInt());
            
            var i = -1;
            foreach (var item in proyeccion)
            {
                i++;
                Chart1.Series[0].Points[i].YValues[0] = Convert.ToDouble(item.totalProyectado);
                Chart1.Series[1].Points[i].YValues[0] = Convert.ToDouble(item.totalComprado);

            }

            itemGridView.DataSource = proyeccion;
            itemGridView.DataBind();
        
            chardUPNL.Update();
            gridUPNL.Update();
            

        }

        protected void CancelItem(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);

                gv.EditIndex = -1;
                gv.FooterRow.Visible = true;
                BindDataItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void periodoDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                BindDataItem();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

      




    }
    
}